<script setup lang="ts">
import type { VxeGridProps, VxeTableInstance } from 'vxe-table'

import { useAddOrEditRate, useGetPricingReportList, useGetRateByProductId } from '@fl/api/purchase'
import { SearchTable } from '@fl/components'
import SubmitBtn from '@fl/components/submit-btn.vue'
import { cloneDeep } from 'lodash-es'
import NP from 'number-precision'

import { PRICING_PRODUCT_STATUS_MAP } from '../goods-management/constant'

const props = defineProps<{
    detailData: {
        calcRule: string
        categoryId: string
        categoryName: string
        explanation: string
        priceProId: string
        productId: string
        productName: string
        specs: string
        status: number
    }
}>()
const emit = defineEmits<{
    publish: []
}>()

const router = useRouter()

const productId = computed(() => props.detailData.productId)

const {
    data: pricingReportListData,
    isLoading: isGetPricingReportListLoading,
    refetch: refetchPricingReportList,
} = useGetPricingReportList(productId)
const { data: rateData, isLoading: isGetRateByProductIdLoading, refetch: refetchRateByProductId } = useGetRateByProductId(productId)
const { isPending: isAddOrEditRatePending, mutate: addOrEditRate } = useAddOrEditRate()

const isSubmitLoading = computed(() => isAddOrEditRatePending.value)
const isNotPublished = computed(() => props.detailData.status === PRICING_PRODUCT_STATUS_MAP.NOT_PUBLISHED)

// #region Collect Table
const isCollectTableLoading = computed(() => isGetRateByProductIdLoading.value)
const collectTableData = ref<any[]>([])

const collectGridOptions = reactive<VxeGridProps>({
    align: 'left',
    border: 'inner',
    columns: [
        { field: 'mgmtRate', slots: { default: 'mgmt_rate' }, title: '管理费率', width: 250 },
        { field: 'mgmtFee', slots: { default: 'mgmt_fee' }, title: '管理费' },
        { field: 'profit', slots: { default: 'profit' }, title: '利润率', width: 250 },
        { field: 'profitAmount', slots: { default: 'profit_amount' }, title: '利润额' },
        { field: 'rate', slots: { default: 'rate' }, title: '税率', width: 250 },
        { field: 'taxes', slots: { default: 'taxes' }, title: '税金' },
        { field: 'totalQuote', slots: { default: 'total_quote' }, title: '除税价' },
        { field: 'taxIncludedPrice', slots: { default: 'tax_included_price' }, title: '含税价' },
        // { field: 'taxIncludedUnitPrice', slots: { default: 'tax_included_unit_price' }, title: '含税综合单价' },
    ],
    headerRowClassName: 'bg-white text-[#86909C] text-[14px]',
    height: undefined,
})
// #endregion

// #region Compose Table
const isComposeTableLoading = computed(() => isGetPricingReportListLoading.value)
const composeTableRef = ref<VxeTableInstance>()
const composeTableData = ref<any[]>([])

const composeGridOptions = reactive<VxeGridProps>({
    columns: [
        { field: 'categoryName', title: '名称', treeNode: true },
        { field: 'model', title: '规格型号' },
        { field: 'usage', title: '计算用量' },
        { field: 'unit', title: '单位' },
        { field: 'price', formatter: formatPrice, title: '综合单价' },
        { field: 'taxFreeTotalPrice', formatter: formatPrice, title: '税前总价' },
        // { field: 'costProportion', title: '造价占比' },
    ],
    headerRowClassName: 'text-[#86909C] text-[14px]',
    height: undefined,
    treeConfig: { expandAll: true, parentField: 'parentId', rowField: 'id' },
})

function formatPrice({ cellValue }) {
    return Number.isNaN(Number.parseFloat(cellValue)) ? '' : `${cellValue}元`
}
// #endregion

// #region UI Listener
function onPublishBtnClick() {
    onSaveBtnClick(true)
}

function onSaveBtnClick(publishOnSuccess: boolean = false) {
    const rowData = collectTableData.value?.[0]
    const params = {
        id: rateData.value?.id,
        mgmtRate: rowData?.mgmtRate,
        productId: productId.value,
        profit: rowData?.profit,
        rate: rowData?.rate,
    }
    addOrEditRate(params, {
        onSuccess() {
            refetchRateByProductId()
            if (publishOnSuccess) {
                emit('publish')
            }
            else {
                ElMessage.success('操作成功')
            }
        },
    })
}

function onCancelBtnClick() {
    router.back()
}

function onRateChange(row: any, key: string) {
    row[key] = Math.abs(row[key]?.replace(
        /^(-)*(\d+)\.(\d).*$/,
        '$1$2.$3',
    ))
}
// #endregion

function computePrice(row: any, rate: number) {
    return NP.round(Number(row.taxFreeTotalPrice) * Number(rate) / 100, 4)
}

function computeTaxes(row: any) {
    const mgmtFee = computePrice(row, row.mgmtRate)
    const profitAmount = computePrice(row, row.profit)
    return NP.round((row.taxFreeTotalPrice + mgmtFee + profitAmount) * Number(row.rate) / 100, 4)
}

function computeTotalQuote(row: any) {
    const mgmtFee = computePrice(row, row.mgmtRate)
    const profitAmount = computePrice(row, row.profit)
    return NP.round(row.taxFreeTotalPrice + mgmtFee + profitAmount, 4)
}

function computeTaxIncludedPrice(row: any) {
    const taxes = computeTaxes(row)
    const mgmtFee = computePrice(row, row.mgmtRate)
    const profitAmount = computePrice(row, row.profit)
    return NP.round(taxes + mgmtFee + profitAmount + row.taxFreeTotalPrice, 4)
}

function displayPrice(num: number) {
    if (Number.isNaN(num)) {
        return '-'
    }
    return `${num}元`
}

function expandTable() {
    const $composeTable = (composeTableRef.value as any)?.tableInstance
    if ($composeTable) {
        $composeTable.setAllTreeExpand(true)
    }
}

watchEffect(() => {
    collectTableData.value = [{
        ...cloneDeep(rateData.value),
        taxFreeTotalPrice: pricingReportListData.value?.[0]?.taxFreeTotalPrice,
    }]
    composeTableData.value = cloneDeep(pricingReportListData.value)
})

const data = computed(() => ({ }))

defineExpose({
    data,
    expandTable,
    refetchPricingReportList,
})
</script>

<template>
    <el-container class="h-full">
        <el-main class="bg-white">
            <el-row>
                <el-col :span="24">
                    <span class="text-[20px] font-semibold">单价汇总</span>
                </el-col>

                <el-col :span="24"
                        class="mt-20"
                >
                    <div>
                        <SearchTable v-bind="collectGridOptions"
                                     :loading="isCollectTableLoading"
                                     :data="collectTableData"
                        >
                            <template #total_quote="{ row }">
                                <span class="inline-block text-left">{{ displayPrice(computeTotalQuote(row)) }}</span>
                            </template>

                            <template #rate="{ row }">
                                <el-input v-model="row.rate"
                                          placeholder="请输入税率"
                                          type="number"
                                          class="!w-[60%]"
                                          @change="onRateChange(row, 'rate')"
                                />

                                <span class="ml-16 inline-block text-left">%</span>
                            </template>

                            <template #taxes="{ row }">
                                <span class="inline-block text-left">{{ displayPrice(computeTaxes(row)) }}</span>
                            </template>

                            <template #mgmt_rate="{ row }">
                                <el-input v-model="row.mgmtRate"
                                          placeholder="请输入管理费率"
                                          type="number"
                                          class="!w-[60%]"
                                          @change="onRateChange(row, 'mgmtRate')"
                                />

                                <span class="ml-16 inline-block text-left">%</span>
                            </template>

                            <template #mgmt_fee="{ row }">
                                <span class="inline-block text-left">{{ displayPrice(computePrice(row, row.mgmtRate)) }}</span>
                            </template>

                            <template #profit="{ row }">
                                <el-input v-model="row.profit"
                                          placeholder="请输入利润率"
                                          type="number"
                                          class="!w-[60%]"
                                          @change="onRateChange(row, 'profit')"
                                />

                                <span class="ml-16 inline-block text-left">%</span>
                            </template>

                            <template #profit_amount="{ row }">
                                <span class="inline-block text-left">{{ displayPrice(computePrice(row, row.profit)) }}</span>
                            </template>

                            <template #tax_included_price="{ row }">
                                <span class="text-[#dA0004]">{{ displayPrice(computeTaxIncludedPrice(row)) }}</span>
                            </template>

                            <!-- <template #tax_included_unit_price="{ row }">
                                <span class="text-[#dA0004]">{{ row.taxIncludedUnitPrice }}</span>
                            </template> -->
                        </SearchTable>
                    </div>
                </el-col>

                <el-col :span="24"
                        class="mt-50"
                >
                    <span class="text-[20px] font-semibold">单价组成</span>
                </el-col>

                <el-col :span="24"
                        class="mt-20"
                >
                    <div>
                        <SearchTable v-bind="composeGridOptions"
                                     ref="composeTableRef"
                                     :loading="isComposeTableLoading"
                                     :data="composeTableData"
                        />
                    </div>
                </el-col>

                <el-col :span="24"
                        class="mt-50 justify-center !flex"
                >
                    <SubmitBtn v-if="isNotPublished"
                               type="primary"
                               :loading="isSubmitLoading"
                               @click="onPublishBtnClick"
                    >
                        发布
                    </SubmitBtn>

                    <SubmitBtn v-if="isNotPublished"
                               type="primary"
                               :loading="isSubmitLoading"
                               @click="onSaveBtnClick"
                    >
                        保存
                    </SubmitBtn>

                    <el-button @click="onCancelBtnClick">
                        取消
                    </el-button>
                </el-col>
            </el-row>
        </el-main>
    </el-container>
</template>

<style scoped lang="scss">
:deep(.vxe-table--body-wrapper) {
    min-height: 48px !important;
}
:deep(.vxe-grid--toolbar-wrapper) {
    display: none;
}
</style>
